import os
import sys
import pygame

try:
    __file__
except NameError as e:
    from whereis import mymain
    rootdir = mymain()
else:
    rootdir = os.path.dirname(os.path.dirname(__file__))

sys.path.insert(0, rootdir)
from lib import color
sys.path.pop(0)


def render(font, text, color=color.black, center=False, line_gap=0):
    '''render(font, text, color=color.black, center=False) -> Surface
    center is used when text is multi line. If center=True then each line is centered
    line_gap is used when text is multi line. It decide the gap of each line'''
    if not '\n' in text:
        return font.render(text, True, color, None)

    lines = text.splitlines()
    surfs = []
    for each in lines:
        surfs.append(font.render(each, True, color, None))

    width = 0
    height = 0
    for each in surfs:
        w, h = each.get_rect().size
        width = max(width, w)
        height = max(height, h)

    surf = pygame.Surface((width, height), flags=pygame.SRCALPHA)
    for each in surfs:
        rect = each.get_rect()
        top = 0
        if center:
            w = rect.width
            left = (width - w) / 2
        else:
            left = 0
        surf.blit(each, (left, top))
        top += line_gap

    return surf
